package com.cszjzx.member.dao;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.cszjzx.member.po.Master;

public class MasterDAOImpl implements MasterDAO,RowMapper{
    private JdbcHelper helper;
    public MasterDAOImpl() throws IOException {
    	helper=new JdbcHelper();
    }
    
	public void add(Master m) throws SQLException {
		String sql ="insert into master (masterid,password,issuper,module,departmentid) value (?,?,?,?,?)";
		int issuper=m.isIssuper()?1:0;
		Object []args={m.getMasterid(),m.getPassword(),issuper,m.getModule(),m.getDepartmentid()};
		helper.executeUpdate(sql, args);
	}

	public void delete(String  masterid) throws SQLException {
		String sql ="delete from master where masterid =?";
		Object [] args={masterid};
		helper.executeUpdate(sql, args);
	}

	public void update(Master m) {
		String sql = "update master set password = ? where id = ?";
		Object [] args={m.getPassword(),m.getId()};
		try {
			helper.executeUpdate(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unchecked")
	public Master find(String masterId,int module) throws ClassNotFoundException, SQLException, IOException {
		String sql ="select *from master where masterid = ? and module = ?";
		Object []args={masterId,module};
		List<Master> list=helper.executeQuery(sql, args, this);
	    if(list.isEmpty())
	    	return null;
	    else
	    	return (Master) list.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Master> findAll(int module) throws ClassNotFoundException, SQLException, IOException {
		String sql ="select * from master where module = ?";
		Object[]args={module};
		return helper.executeQuery(sql, args, this);
	}

	public Object mapRow(ResultSet rs) throws SQLException, ClassNotFoundException, IOException {
		boolean issuper=(rs.getInt("issuper")!=0)?true:false;
		Master master=new Master(rs.getInt("id"), rs.getString("masterid"), rs.getString("password"),issuper,rs.getInt("module"));
		master.setDepartmentid(rs.getInt("departmentid"));
		return master;
	}
	//测试
	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
		System.out.println(1);
		System.out.println(new MasterDAOImpl().find("admin",1).getDepartmentid());
	}
}
